package com.Controller;

import com.Service.GroupService;
import com.pojo.GroupActivityVO;
import com.pojo.GroupJoinVO;
import com.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import jakarta.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/front/group")
public class FrontGroupController {
    @Autowired
    private GroupService groupService;

    @Autowired
    private HttpSession session;

    @GetMapping("/my")
    public String myGroups(Model model) {
        User user = (User) session.getAttribute("user");
        List<GroupJoinVO> list = groupService.getGroupsByUser(user.getId());
        System.out.println(list);
        model.addAttribute("groupList", list);
        return "front/group_list";
    }

    @GetMapping("/detail")
    public String groupDetail(@RequestParam("id") Long id, Model model) {

        GroupActivityVO detail = groupService.getGroupDetail(id);   //拼团活动id
        System.out.println("groupDetail = " + detail);
        model.addAttribute("group", detail);
        return "front/group_detail";
    }

    @PostMapping("/join")
    public String joinGroup(@RequestParam("activityId") Long id) {
        User user = (User) session.getAttribute("user");
        groupService.joinGroup(id, user.getId());
        return "redirect:/front/group/my";
    }

        @PostMapping("/initiate")
        public String initiateGroup(@RequestParam("activityId") Long activityId,
                                    RedirectAttributes redirectAttributes) {
            User user = (User) session.getAttribute("user");
            try {
                groupService.initiateGroup(activityId, user.getId());
            } catch (RuntimeException e) {
                // 将错误信息保存到 redirectAttributes
                redirectAttributes.addFlashAttribute("error", e.getMessage());
            }
            return "redirect:/front/product/detail?id=" + activityId; // 回到商品详情页
        }
}
